#include "StdAfx.h"
#include "TCP.h"

#include "util.h"

using namespace SocketCtrl4;

TCP::TCP(void)
: _socket(INVALID_SOCKET)
{
}

TCP::~TCP(void)
{
	close();
}

SOCKET TCP::socket(SOCKET sock)
{
	if (_socket != INVALID_SOCKET)
	{
		return false;
	}

	if (sock == INVALID_SOCKET)
	{
		sock = ::socket(AF_INET, SOCK_STREAM, 0);

		if (sock != INVALID_SOCKET)
		{
			_socket = sock;
		}
	}
	else
	{
		_socket = sock;
	}

	return _socket;
}

void TCP::close()
{
	if (_socket != INVALID_SOCKET)
	{
		closesocket(_socket);

		_socket = INVALID_SOCKET;
	}
}

int TCP::bind(int port, const std::string &ip)
{
	sockaddr addr;
	int addrLen = sizeof(addr);

	fillSockAddr(addr, ip, port);

	int res = ::bind(_socket, &addr, addrLen);

	return res;
}

int TCP::listen(int backlog)
{
	int res = ::listen(_socket, backlog);

	return res;
}

SOCKET TCP::accept(std::string &ip, int &port)
{
	sockaddr addr;
	int addrLen = sizeof(addr);

	SOCKET s = ::accept(_socket, &addr, &addrLen);

	splitSockAddr(addr, ip, port);

	return s;
}

int TCP::connect(const std::string &ip, int port)
{
	sockaddr addr;
	::fillSockAddr(addr, ip, port);

	int res = ::connect(_socket, &addr, sizeof(addr));

	return res;
}

int TCP::recv(char *buf, int len, int flags)
{
	int res = ::recv(_socket, buf, len, flags);

	return res;
}

int TCP::send(const char *buf, int len, int flags)
{
	int res = ::send(_socket, buf, len, flags);

	return res;
}

int TCP::getsocketopt(int level, int optname, char *optval, int *optlen)
{
	int res = ::getsockopt(_socket, level, optname, optval, optlen);

	return res;
}

int TCP::setsocketopt(int level, int optname, const char FAR * optval, int optlen)
{
	int res = ::setsockopt(_socket, level, optname, optval, optlen);

	return res;
}

int TCP::getpeername(std::string &ip, int &port)
{
	sockaddr addr;
	int addrLen = sizeof(addr);

	fillSockAddr(addr, ip, port);

	int res = ::getpeername(_socket, &addr, &addrLen);

	if (res != SOCKET_ERROR)
	{
		splitSockAddr(addr, ip, port);
	}

	return res;
}

int TCP::getsockname(std::string &ip, int &port)
{
	sockaddr addr;
	int addrLen = sizeof(addr);

	fillSockAddr(addr, ip, port);

	int res = ::getsockname(_socket, &addr, &addrLen);

	if (res != SOCKET_ERROR)
	{
		splitSockAddr(addr, ip, port);
	}

	return res;
}

int TCP::WSAAsyncSelect(HWND hWnd, unsigned int wMsg, long lEvent)
{
	int res = ::WSAAsyncSelect(_socket, hWnd, wMsg, lEvent);

	return res;
}